package com.zoulj.task;

import com.alibaba.fastjson.JSONObject;
import com.zoulj.util.RedisOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class DeviceBaseInfoJobs {

    private static final String SP4_DEVICERULEINFO = "SP4_DeviceRuleInfo";

    //Timestamp_Local":"2021-04-07 22:16:24.708"
    private static final String TIMESTAMP_LOCAL = "Timestamp_Local";

    //设置默认值防止报错
    @Value("${deviceBaseInfo.liveTime.job.enabled:false}")
    private boolean jobEnabled;

    /*@Autowired
    private IDeviceBaseInfoDao deviceBaseInfoDao;*/

    @Autowired
    private RedisOperator redisOperator;

    //半小时一次
    @Scheduled(cron = "0 0/30 * * * ? ")
    @Async
    public void cronJobs() {
        log.info("DeviceBaseInfoJobs================>start.");
        if (!jobEnabled) return;
        //拿出所有的baseinfoId
        //List<String> baseInfoIdList = deviceBaseInfoDao.getAllDeviceInfoId();
        List<String> baseInfoIdList = new ArrayList<>();
        //从redis拿到所有的实时工况时间,之后再入表
        if (CollectionUtils.isEmpty(baseInfoIdList)) {
            return;
        }
        baseInfoIdList.forEach(id -> {
            String val = redisOperator.get(SP4_DEVICERULEINFO + ":" + id);
            String liveTime = "";
            if (StringUtils.isNotEmpty(val)) {
                JSONObject jsonObject = JSONObject.parseObject(val);
                if (jsonObject.containsKey(TIMESTAMP_LOCAL)) {
                    liveTime = jsonObject.getString(TIMESTAMP_LOCAL);
                }
            }
            if (StringUtils.isNotEmpty(liveTime)) {
                //boolean updateStatus = deviceBaseInfoDao.updateLiveTime(id, liveTime);
                boolean updateStatus = false;
                log.info("DeviceBaseInfoJobs:====>baseInfoId{},liveTime{},updateStatus{}", id, liveTime, updateStatus);
            }
        });
        log.info("DeviceBaseInfoJobs:================>end.");
    }
}
